import torch
import torch.nn as nn
import torch.nn.functional as F
import CBAM as cbam


class SimpleCNNWithCBAM(nn.Module):
    def __init__(self, num_classes=10):
        super(SimpleCNNWithCBAM, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)  # 输入通道数为 3，输出通道数为 64
        self.cbam1 = cbam.CBAM(64)  # 在第一层卷积后添加 CBAM 模块
        self.pool = nn.MaxPool2d(2, 2)  # 池化层
        self.conv2 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
        self.cbam2 = cbam.CBAM(128)  # 在第二层卷积后添加 CBAM 模块
        self.fc1 = nn.Linear(128 * 8 * 8, 256)  # 全连接层
        self.fc2 = nn.Linear(256, num_classes)  # 输出层

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.cbam1(x)  # 应用 CBAM 模块
        x = self.pool(x)

        x = self.conv2(x)
        x = F.relu(x)
        x = self.cbam2(x)  # 应用 CBAM 模块
        x = self.pool(x)

        x = x.view(x.size(0), -1)  # 展平
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# 测试融合后的模型
if __name__ == '__main__':
    DEVICE = 'mps' if torch.backends.mps.is_available() else 'cpu'  # 支持 MPS 则使用，否则使用 CPU
    print(f"Using device: {DEVICE}")
    model = SimpleCNNWithCBAM(num_classes=10).to(DEVICE)
    input = torch.randn(1, 3, 32, 32).to(DEVICE)  # CIFAR-10 图像大小为 32x32
    output = model(input)
    print(f"Output shape: {output.shape}")